﻿
using System ;

using MskEdit.Msk.Representation ;


namespace MskEdit.Msk.Model
{    
    public class MskLineKey
    {
        private static      MskLineKey  nullLineKey_ = new MskLineKey() ;
        private             MskPageKey  pageKey_ ;
        private             string      fieldName_ ;


        private MskLineKey() {
            pageKey_    = MskPageKey.NullPageKey ;
            fieldName_  = StringField.FieldName.PadRight( "" ) ;
        }


        private MskLineKey( MskPageKey pageKey, string fieldName ) {
            pageKey_    = pageKey ;
            fieldName_  = fieldName ;
        }
        
        
        static public MskLineKey TryFrom( string line, MskLineKey fallbackValue ) {

            MskPageKey pageKey = MskPageKey.TryFrom( line, null ) ;
            if ( pageKey == null )
                return fallbackValue ;
            
            string fieldName = StringField.FieldName.TryFrom( line, null ) ;
            if ( fieldName == null )
                return fallbackValue ;
                
            MskLineKey mskLineKey = new MskLineKey( pageKey, fieldName ) ;
            
            return mskLineKey ;
        }
        
        
        static public MskLineKey TriedFromLine( string line, MskLineKey fallbackValue ) {

            MskPageKey  pageKey     = MskPageKey.TryFrom( line, fallbackValue.PageKey ) ;
            string      fieldName   = StringField.FieldName.TryFrom( line, fallbackValue.FieldName ) ;
            
            return new MskLineKey( pageKey, fieldName ) ;
        }
        
        
        public static MskLineKey NullLineKey {
            get { return nullLineKey_ ; }
        }

                
        public MskPageKey PageKey {
            get { return pageKey_ ; }
        }
        
        
        public string FieldName {
            get { return fieldName_ ; }
        }


        public override String ToString() {
        
            string lineKeyAsString = 
                pageKey_.ToString() +
                "." + 
                fieldName_.ToString() ;
                
            return lineKeyAsString ;
        }
        
        
        public override bool Equals( object obj ) {
        
            MskLineKey that = ( MskLineKey ) obj ;
            
            if ( ! that.pageKey_.Equals( this.pageKey_ ) )
                return false ;
            
            if ( ! that.fieldName_.Equals( this.fieldName_ ) )
                return false ;
                
            return true ;
        }


        public override int GetHashCode() {
        
            var pageKeyHashCode = this.pageKey_.GetHashCode() ;
            var fieldNameHashCode = this.fieldName_.GetHashCode() ;
            
            var hashCode = pageKeyHashCode ^ fieldNameHashCode ;
            
            return hashCode ;
        }

    }
}
